package com.chuangke.common.utils;

import java.util.Stack;

import cn.hutool.core.util.StrUtil;

/**
 * 进制转换
 */
public class HexUtils {

    private static final String numStr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final char[] array = numStr.toCharArray();

    // 10进制转为其他进制，除留取余，逆序排列
    public static String tenToN(long number, int n) {
        long rest = number;
        Stack<Character> stack = new Stack<>();
        StringBuilder result = new StringBuilder(0);
        while (rest != 0) {
            stack.add(array[Long.valueOf((rest % n)).intValue()]);
            rest = rest / n;
        }
        while (!stack.isEmpty()) {
            result.append(stack.pop());
        }
        return StrUtil.isEmpty(result) ? array[0] + "" : result.toString();
    }

    // 其他进制转为10进制，按权展开
    public static long nToTen(String number, int n) {
        char[] ch = number.toCharArray();
        int len = ch.length;
        if (n == 10) {
            return Long.parseLong(number);
        }
        long result = 0, base = 1;
        for (int i = len - 1; i >= 0; i--) {
            int index = numStr.indexOf(ch[i]);
            result += index * base;
            base *= n;
        }
        return result;
    }

}
